using System;
using System.Net;
using System.Net.Sockets;
using Servlets.Server;

namespace Servlets.Sockets
{
	class TcpListener : IListener
	{
		private System.Net.Sockets.TcpListener listener;
		
		/// <summary>
		/// Creates a new <see cref="Servlets.IListener"/> with a default IPAddress of 127.0.0.1 on the given port
		/// </summary>
		/// <param name="port">
		/// A <see cref="System.Int32"/>. The port to listen on.
		/// </param>
		public TcpListener(int port) : this(IPAddress.Parse("127.0.0.1"), port) {}
		
		/// <summary>
		/// Creates a new <see cref="Servlets.IListener"/> with the given IPAddress on the given port
		/// </summary>
		/// <param name="address">
		/// A <see cref="IPAddress"/>
		/// </param>
		/// <param name="port">
		/// A <see cref="System.Int32"/>. The port to listen on.
		/// </param>		
		public TcpListener(IPAddress address, int port)
		{
			listener = new System.Net.Sockets.TcpListener(address, port);
		}
		
		/// <summary>
		/// Starts the listener so it can start accepting clients
		/// </summary>
		public void Start() {
			listener.Start();
		}
		
		/// <summary>
		/// Blocks until a connection is established. Returns an IClient to communicate with the connected client.
		/// The Start() must be called first.
		/// </summary>
		/// <returns>
		/// A <see cref="IClient"/> to communicate with.
		/// </returns>
		public IClient AcceptClient() {
			IClient client = new TcpClient(listener.AcceptTcpClient());
			return client;
		}
		
		/// <summary>
		/// Stops and cleans up the listener
		/// </summary>
		public void Dispose() {
			listener.Stop();
		}
	}
}

